# -*- encoding:utf-8 -*-
"""
@作者：ven
@文件名：logUtil.py
@时间：2021-10-22  14:17
@文档说明:
"""

import logging
import sys,datetime
from os import makedirs
from os.path import dirname, exists


loggers = {}

LOG_ENABLED = True  # 是否开启日志
LOG_TO_CONSOLE = False  # 是否输出到控制台
LOG_TO_FILE = True  # 是否输出到文件


LOG_PATH = '../logs/'  # 日志文件路径
LOG_NAME = f"{datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.log"
LOG_LEVEL = 'DEBUG'  # 日志级别
LOG_FORMAT = '%(asctime)s - %(levelname)s  - %(filename)s - %(name)s - %(lineno)d - %(module)s - %(message)s'  # 每条日志输出格式
APP_ENVIRONMENT = 'dev'  # 运行环境，如测试环境还是生产环境

def get_logger(name=None):
    """
    get logger by name
    :param name: name of logger
    :return: logger
    """
    global loggers

    if not name: name = __name__

    if loggers.get(name):
        return loggers.get(name)

    logger = logging.getLogger(name)
    logger.setLevel(LOG_LEVEL)

    # 输出到控制台
    if LOG_ENABLED and LOG_TO_CONSOLE:
        stream_handler = logging.StreamHandler(sys.stdout)
        stream_handler.setLevel(level=LOG_LEVEL)
        formatter = logging.Formatter(LOG_FORMAT)
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)

    # 输出到文件
    if LOG_ENABLED and LOG_TO_FILE:
        # 如果路径不存在，创建日志文件文件夹
        log_dir = dirname(LOG_PATH)
        if not exists(log_dir): makedirs(log_dir)
        # 添加 FileHandler
        file_handler = logging.FileHandler(LOG_PATH+LOG_NAME, mode='a+',encoding='utf-8')
        file_handler.setLevel(level=LOG_LEVEL)
        formatter = logging.Formatter(LOG_FORMAT)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)



    # 保存到全局 loggers
    loggers[name] = logger
    return logger

if __name__ == '__main__':
    log = get_logger()
    log.info('调试信息')
    log.error('错误信息')